package com.yuntian.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yuntian.Dto.CartPageQueryDto;
import com.yuntian.Vo.admin.CartVO;
import com.yuntian.entity.Cart;
import com.yuntian.mapper.CartMapper;
import com.yuntian.result.PageResult;
import com.yuntian.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    //查询购物车列表
    public PageResult selectAll(CartPageQueryDto cartPageQueryDto) {

        PageHelper.startPage(cartPageQueryDto.getPage(),cartPageQueryDto.getPageSize());
        Page<CartVO> page = cartMapper.selectTotal(cartPageQueryDto);
        long total = page.getTotal();
        List<CartVO> result = page.getResult();

        for (CartVO item : result){
            Integer quantity = item.getQuantity();
            // 计算小计金额
            BigDecimal totalPrice = item.getPrice().multiply(new BigDecimal(quantity));
            item.setTotalPrice(totalPrice);
        }
        return new PageResult(total,result);
    }

    //添加购物车
    public void insertCart(Cart cart) {
        // 检查购物车中是否已经存在该商品
        Cart existCart =  cartMapper.selectCartByUserIdAndProductId(cart.getUserId(), cart.getProductId());
        if (existCart != null) {
            // 如果存在，则更新数量
            int oldQuantity = existCart.getQuantity();
            int newQuantity = oldQuantity + cart.getQuantity();
            existCart.setQuantity(newQuantity);
            cartMapper.updateCart(existCart);
        }
        cart.setCreateTime(LocalDateTime.now());
        cartMapper.insertCart(cart);
    }

    public void updateCart(Cart cart) {
        //更新购物车商品数量
        cart.setCreateTime(LocalDateTime.now());
        cartMapper.updateCart(cart);
    }


    public void deleteCart(Integer cartId) {
        cartMapper.deleteCart(cartId);
    }

    //清空购物车
    public void deleteCartByUserId(Long userId) {
        cartMapper.deleteCartByUserId(userId);

    }

    //多条删除
    public void deleteCartByIds(List<Integer> ids) {
        // 遍历id列表，逐个删除
        for (Integer id : ids) {
            cartMapper.deleteCart(id);
        }
    }
}
